/*******************************************************************************
 * Package: com.hngtrust.iir.third.service.impl
 * Type:    ChinaTrustRegistrationServiceImpl
 * Date:    2021/10/14 10:26
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.third.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.company.entity.Company;
import com.hngtrust.iir.company.service.CompanyService;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.third.contant.Contant;
import com.hngtrust.iir.third.controller.dto.CtrRelationDTO;
import com.hngtrust.iir.third.controller.dto.RelatedPartiesExportVO;
import com.hngtrust.iir.third.controller.dto.RelatedPartiesRequestVO;
import com.hngtrust.iir.third.controller.dto.RelatedPartiesResponseVO;
import com.hngtrust.iir.third.controller.dto.RelatedPartiesVO;
import com.hngtrust.iir.third.controller.dto.RelationExportDTO;
import com.hngtrust.iir.third.entity.CtrLog;
import com.hngtrust.iir.third.entity.CtrRelation;
import com.hngtrust.iir.third.service.CtrLogService;
import com.hngtrust.iir.third.service.CtrRelationService;
import com.hngtrust.iir.third.service.RelatedPartiesService;
import com.hngtrust.iir.third.util.MD5Util;
import com.hngtrust.iir.user.entity.User;
import com.tiger.excel.ExcelUtils;
import com.tiger.util.MyHttpClient;
import com.tiger.web.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 调用中信登第三方接口(关联方信息)
 *
 * @author Yujiaqi
 * @date 2021/10/14 10:26
 */
@Service
@Slf4j
public class RelatedPartiesServiceImpl implements RelatedPartiesService {
    
    @Value("${relatedPartiesUrl.url}")
    private String relatedPartiesUrl;
    
    @Value("${zxd.cust_no1}")
    private String custNo1;
    
    @Value("${zxd.cust_no2}")
    private String custNo2;
    
    @Value("${zxd.md5key}")
    private String md5key;
    
    @Autowired
    private MyIdGenerator myIdGenerator;
    
    /** 中信登接口日志表 */
    @Autowired
    private CtrLogService ctrLogService;
    
    /** 中信登关联方 */
    @Autowired
    private CtrRelationService ctrRelationService;
    
    /** 投研公司表 */
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private PageService pageService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    @Qualifier("localFileService")
    private FileService localFileService;
    
    /**
     * 关联方信息查询
     * @param relatedPartiesVO
     * @return
     */
    @Override
    public ResponseInfo<PageResult<CtrRelationDTO>> addRelatedParties(ReqDTO<RelatedPartiesVO> relatedPartiesVO)
            throws JsonProcessingException {
        //根据公司id或者key到中信登接口日志表查询数据，如果有则返回对应的受益人，如果没有则执行下方法
        String param;
        if (relatedPartiesVO.getContent().getCompId() != null) {
            param = String.valueOf(relatedPartiesVO.getContent().getCompId());
        } else if (StringUtils.isNotBlank(relatedPartiesVO.getContent().getKey())) {
            param = relatedPartiesVO.getContent().getKey();
        } else {
            return new ResponseInfo();
        }
        Long ctrLogId = ctrLogService.queryCtrLog(param, Contant.GLF_INTERFACE_TYPE);
        //判断是否为空，如果不为空，直接返回对应受益人数据，为空则调用中信登接口查询
        if (ctrLogId != null) {
            CtrRelation ctrRelation = new CtrRelation();
            ctrRelation.setLogId(ctrLogId);
            //关联方类型
            ctrRelation.setPartyType(relatedPartiesVO.getContent().getPartyType());
            //下面四个参数都是 监管要求 下拉框的参数
            ctrRelation.setCirc(relatedPartiesVO.getContent().getCirc());
            ctrRelation.setAccount(relatedPartiesVO.getContent().getAccount());
            ctrRelation.setSse(relatedPartiesVO.getContent().getSse());
            ctrRelation.setSehk(relatedPartiesVO.getContent().getSehk());
            //关联方
            ctrRelation.setPartyName(relatedPartiesVO.getContent().getPartyName());
            // 返回给前端数据
            PageResult<CtrRelation> page = pageService.page(relatedPartiesVO.getPageParam(), () -> ctrRelationService.queryList(ctrRelation,relatedPartiesVO.getContent().getRegulatoryRequirementsSelectStatus()));
            if (page.getRows().size() == 0) {
                CtrLog ctrLog = ctrLogService.queryById(ctrLogId);
                return new ResponseInfo(Contant.SUCCESS, ctrLog.getFailReason());
            }
            //返回给前端数据
            PageResult<CtrRelationDTO> relationDTOPageResult = backToFrontEnd(page, ctrLogId);
            return new ResponseInfo(relationDTOPageResult);
        } else {
            ResponseInfo<PageResult<CtrRelationDTO>> pageResultResponseInfo = thirdData(param, relatedPartiesVO);
            return pageResultResponseInfo;
        }
    }
    
    private PageResult<CtrRelationDTO> backToFrontEnd(PageResult<CtrRelation> page,Long ctrLogId){
        //数据处理，返回给前端数据
        PageResult<CtrRelationDTO> relationDTOPageResult = new PageResult<>();
        //前端列表及模糊条件
        CtrRelationDTO ctrRelationDTOS = new CtrRelationDTO();
        //前端列表
        List<CtrRelationDTO.CtrRelationList> ctrRelationLists = new ArrayList<>();
        
        relationDTOPageResult.setPage(page.getPage());
        List<CtrRelation> rows = page.getRows();
        for (CtrRelation row : rows) {
            CtrRelationDTO.CtrRelationList ctrRelationDTO = new CtrRelationDTO.CtrRelationList();
            ctrRelationDTO.setId(row.getId());
            ctrRelationDTO.setPartyName(row.getPartyName());
            ctrRelationDTO.setPartyType(row.getPartyType());
            ctrRelationDTO.setCreditCode(row.getCreditCode());
            ctrRelationDTO.setOrganizationCode(row.getOrganizationCode());
            //（是否符合银保监—保险系规则、是否符合会计准则、是否符合上交所规则、是否符合联交所规则）  拼起来
            String compWithRegulatoryRequire = compWithRegulatoryRequireData(row);
            ctrRelationDTO.setCompWithRegulatoryRequire(compWithRegulatoryRequire);
            //规则路径链中的编码拼接起来
            String judgmentRule = "";
            String rulePath = row.getRulePath();
            String[] split = rulePath.split("-");
            if (split !=null && split.length > 0) {
                for (String s : split) {
                    String regex = "^[A-Z]{3}[_]([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])$";
                    if (s.matches(regex)) {
                        judgmentRule += s + "、";
                    }
                }
            }
            if (StringUtils.isNotBlank(judgmentRule)) {
                judgmentRule = judgmentRule.substring(0, judgmentRule.length() - 1);
            }
            ctrRelationDTO.setJudgmentRule(judgmentRule);
            ctrRelationDTO.setUpdateTime(row.getCreateTime());
            ctrRelationDTO.setRulePathNumber(row.getRulePathNumber());
            // 规则关系路径，根据;分隔
            int i = 1;
            String rulePath1 = row.getRulePath();
            String substring = rulePath1.substring(1, rulePath1.length() - 1);
            String[] split1 = substring.split(";");
            List<CtrRelationDTO.RuleRelation> ruleRelations = new ArrayList<>();
            if(split1 != null && split1.length > 0){
                for (String s : split1) {
                    CtrRelationDTO.RuleRelation ruleRelation = new CtrRelationDTO.RuleRelation();
                    ruleRelation.setSerialNumber("路径"+i);
                    ruleRelation.setName(s);
                    i++;
                    ruleRelations.add(ruleRelation);
                }
            }
            ctrRelationDTO.setRuleRelation(ruleRelations);
            ctrRelationDTO.setConratePathNumber(row.getConratePathNumber());
            // 关联关系路径，根据;分隔            if(split2 != null && split2.length > 0) {
            int j = 1;
            String conratePath = row.getConratePath();
            String substring1 = conratePath.substring(1, conratePath.length() - 1);
            String[] split2 = substring1.split("},\\{");
            List<CtrRelationDTO.AssociationRelationship> relationships = new ArrayList<>();
            if(split2 != null && split2.length > 0) {
                for (String s : split2) {
                    CtrRelationDTO.AssociationRelationship associationRelationship = new CtrRelationDTO.AssociationRelationship();
                    associationRelationship.setSerialNumber("路径"+j);
                    associationRelationship.setName(s);
                    relationships.add(associationRelationship);
                    j++;
                }
            }
            ctrRelationDTO.setAssociationRelationship(relationships);
            ctrRelationLists.add(ctrRelationDTO);
        }
        
        
        
        ctrRelationDTOS.setLists(ctrRelationLists);
        
        //查询所有数据
        CtrRelation ctrRelation1 = new CtrRelation();
        ctrRelation1.setLogId(ctrLogId);
        List<CtrRelation> ctrRelations = ctrRelationService
                .queryList(ctrRelation1, 0);
        
        ctrRelationDTOS.setRelationInformation(ctrRelations.size());
        Set<String> set = new HashSet<>();
        Set<String> set1 = new HashSet<>();
        List<CtrRelationDTO.RegulatoryRequirements> regulatoryRequirements = new ArrayList<>();
        if(ctrRelations != null && ctrRelations.size() > 0) {
            for (CtrRelation relation : ctrRelations) {
                // 关联方类型下拉
                set.add(relation.getPartyType());
                // 监管要求下拉
                CtrRelationDTO.RegulatoryRequirements regulatoryRequirements1 = new CtrRelationDTO.RegulatoryRequirements();
                String compWithRegulatoryRequire = compWithRegulatoryRequireData(relation);
                boolean add = set1.add(compWithRegulatoryRequire);
                if (add){
                    regulatoryRequirements1.setRegulatoryRequirementsSelect(compWithRegulatoryRequire);
                    regulatoryRequirements1.setCirc(relation.getCirc());
                    regulatoryRequirements1.setAccount(relation.getAccount());
                    regulatoryRequirements1.setSse(relation.getSse());
                    regulatoryRequirements1.setSehk(relation.getSehk());
                    regulatoryRequirements.add(regulatoryRequirements1);
                }
            }
        }
        ctrRelationDTOS.setRelationTypeSelect(set);
        ctrRelationDTOS.setRegulatoryRequirementsSelect(regulatoryRequirements);
        List<CtrRelationDTO> ctrRelationDTOS1 = new ArrayList<>();
        ctrRelationDTOS1.add(ctrRelationDTOS);
        relationDTOPageResult.setRows(ctrRelationDTOS1);
        return relationDTOPageResult;
    }
    
    private static String compWithRegulatoryRequireData(CtrRelation row){
        String compWithRegulatoryRequire = "";
        Integer circ = row.getCirc();
        if(circ != null && circ == 1){
            compWithRegulatoryRequire += Contant.CIRC+"、";
        }
        Integer account = row.getAccount();
        if(account != null && account == 1){
            compWithRegulatoryRequire += Contant.ACCOUT+"、";
        }
        Integer sse = row.getSse();
        if(sse != null && sse == 1){
            compWithRegulatoryRequire += Contant.SSE+"、";
        }
        Integer sehk = row.getSehk();
        if(sehk != null && sehk == 1){
            compWithRegulatoryRequire += Contant.SEHK;
        }
        return compWithRegulatoryRequire;
    }
    
    
    /** 调用中信登关联方方法，用于搜索接口和更新接口 */
    public ResponseInfo<PageResult<CtrRelationDTO>> thirdData(String param,ReqDTO<RelatedPartiesVO> relatedPartiesVO){
        //签名
        String dgtSgnDscMd5 = null;
        //中信登接口日志表ID
        long ctrLogID = myIdGenerator.nextId();
        //请求流水号
        String reqNo = String.valueOf(myIdGenerator.nextId());
        //创建中信登接口日志对象
        CtrLog ctrLog = new CtrLog();
        //判断公司id是否有值，有值则查询公司表（company），没值则确认输入值为（公司名或信用代码或组织机构代码）
        if (relatedPartiesVO.getContent().getCompId() != null) {
            Company company = companyService.queryById(relatedPartiesVO.getContent().getCompId());
            ctrLog.setCompId(company.getId());
            ctrLog.setCompName(company.getName());
            ctrLog.setCreditCode(company.getCreditCode());
            ctrLog.setOrgCode(company.getOrgCode());
            param = company.getName();
            // 签名规则Md5(queryType&queryContent|MD5KEY)
            String dgtSgnDsc = company.getName() + "|" + md5key;
            dgtSgnDscMd5 = MD5Util.mD5Bit32(dgtSgnDsc).toLowerCase();
        } else {
            // 判断规则确定是 信用代码/公司名称/组织机构
            String key = relatedPartiesVO.getContent().getKey();
            String regex = "^[0-9A-Za-z]{18}$";
            String regex1 = "^[a-zA-Z0-9-]{9,10}$";
            //0-企业名称  1-统一社会信用代码  2-组织机构代码
            if (key.matches(regex)) {
                ctrLog.setCreditCode(param);
            } else if (key.matches(regex1)) {
                ctrLog.setOrgCode(param);
            } else {
                ctrLog.setCompName(param);
            }
        }
        Date date = new Date();
        
        ctrLog.setId(ctrLogID);
        ctrLog.setInterfaceType(Contant.GLF_INTERFACE_TYPE);
        ctrLog.setReqNo(reqNo);
        ctrLog.setStatus(Contant.STATUS);
        ctrLog.setCreateTime(date);
        ctrLog.setUpdateTime(date);
        //获取当前登录人
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        ctrLog.setCreateUserId(loginUser.getId());
        ctrLog.setUpdateUserId(loginUser.getId());
        ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_1);
        
        /* 调中信登收益所有人参数列表所需参数 */
        RelatedPartiesRequestVO relatedPartiesRequestVO = new RelatedPartiesRequestVO();
        /** head添加参数 */
        RelatedPartiesRequestVO.Head head = new RelatedPartiesRequestVO.Head();
        
        SimpleDateFormat specificDate = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat hourMinuteAndSecond = new SimpleDateFormat("HHmmssSSS");
        //格式化请求日期
        String specificDate1 = specificDate.format(date);
        //格式化请求时间
        String hourMinuteAndSecond1 = hourMinuteAndSecond.format(date);
        
        if (StringUtils.isNotBlank(relatedPartiesVO.getContent().getKey())) {
            // 签名规则Md5(queryType&queryContent|MD5KEY)
            String dgtSgnDsc = relatedPartiesVO.getContent().getKey() + "|" + md5key;
            dgtSgnDscMd5 = MD5Util.mD5Bit32(dgtSgnDsc).toLowerCase();
        }
        
        head.setTranDt(specificDate1);
        head.setTranTm(hourMinuteAndSecond1);
        head.setCharSet(Contant.CHAR_SET);
        //雪花算法生成唯一流水号
        head.setRqsSeqNo(reqNo);
        head.setSvcCd(Contant.GLF_SVC_CD);
        head.setDgtSgnDsc(dgtSgnDscMd5);
        relatedPartiesRequestVO.setHead(head);
        /** body添加参数 */
        RelatedPartiesRequestVO.Body body = new RelatedPartiesRequestVO.Body();
        body.setCustNo1(custNo1);
        body.setCustNo2(custNo2);
        body.setQueryContent(param);
        body.setPageNo("1");
        body.setPageSize("500");
        relatedPartiesRequestVO.setBody(body);
        //中信登接口日志表 (请求报文)
        String reqContent = JSON.toJSONString(relatedPartiesRequestVO);
        ctrLog.setReqContent(reqContent);
        //中信登接口日志表新增
        ctrLogService.add(ctrLog);
        
        //调用中信登接口（关联方查询）
        String relatedParties = null;
        try {
            log.info("调用中信登关联方接口开始{}");
            MyHttpClient client = new MyHttpClient();
            relatedParties = client.postJson(relatedPartiesUrl, relatedPartiesRequestVO);
            log.info("中信登关联方返回接口数据{}  " + relatedParties);
        } catch (Exception e) {
            ctrLog = new CtrLog();
            ctrLog.setId(ctrLogID);
            ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
            ctrLog.setFailReason("调用中信登第三方接口(关联方) 调用接口异常");
            //修改中信登接口日志表 接口状态 为返回失败
            ctrLogService.modifyById(ctrLog);
            e.printStackTrace();
            log.error("调用中信登第三方接口(受益所有人) 调用接口异常{}");
            return new ResponseInfo("error", "访问中信登第三方接口异常!");
        }
        //拿到中信登返回的totalPage如果>500就在调用一次中信登接口
        RelatedPartiesResponseVO relatedPartiesResponseVO1 = JSON.parseObject(relatedParties, RelatedPartiesResponseVO.class);
        RelatedPartiesResponseVO.RelatedPartiesBody body2 = relatedPartiesResponseVO1.getBody();
        if (body2 != null) {
            String data = relatedPartiesResponseVO1.getBody().getData();
            if (StringUtils.isNotBlank(data)) {
                RelatedPartiesResponseVO.BenerficiaryData benerficiaryData = JSON
                        .parseObject(data, RelatedPartiesResponseVO.BenerficiaryData.class);
                Integer totalCount = benerficiaryData.getPage().getTotalCount();
                if (totalCount > 500) {
                    Integer totalPage = benerficiaryData.getPage().getTotalPage();
                    //获取中信登（受益人）结果
                    List<RelatedPartiesResponseVO.RelatedParties> bene = null;
                    Integer beneSize = 0;
                    String relatedPartiesContent = "";
                    for (int i = 1; i <= totalPage; i++) {
                        try {
                            log.info("调用中信登关联方接口开始{}");
                            //传所以数据再次调用中债登接口
                            //请求流水号
                            String reqNo1 = String.valueOf(myIdGenerator.nextId());
                            head.setRqsSeqNo(reqNo1);
                            body.setPageNo(String.valueOf(i));
                            body.setPageSize("500");
                            MyHttpClient client = new MyHttpClient();
                            relatedParties = client.postJson(relatedPartiesUrl, relatedPartiesRequestVO);
                            log.info("中信登关联方返回接口数据{}  " + relatedParties);
                            relatedPartiesContent += relatedParties;
                            
                            RelatedPartiesResponseVO relatedPartiesResponseVO = JSON.parseObject(relatedParties, RelatedPartiesResponseVO.class);
                            RelatedPartiesResponseVO.RelatedPartiesBody body1 = relatedPartiesResponseVO.getBody();
                            if (body1 != null) {
                                String data2 = relatedPartiesResponseVO.getBody().getData();
                                RelatedPartiesResponseVO.BenerficiaryData benerficiaryData1 = null;
                                if (StringUtils.isNotBlank(data2)) {
                                    benerficiaryData1 = JSON.parseObject(data2, RelatedPartiesResponseVO.BenerficiaryData.class);
                                }
                                if (StringUtils.isNotBlank(data2)) {
                                    bene = benerficiaryData1.getRelatedParties();
                                    beneSize += bene.size();
                                }
                                //获取返回状态
                                String retCd = relatedPartiesResponseVO.getHead().getRetCd();
                                if (retCd.equals(Contant.RET_CD)) {
                                    String resultDetailCode = relatedPartiesResponseVO.getBody().getResultDetailCode();
                                    if ("00".equals(resultDetailCode)) {
                                        List<CtrRelation> ctrCtrRelations = new ArrayList<>();
                                        if (bene != null && bene.size() > 0) {
                                            for (RelatedPartiesResponseVO.RelatedParties benerficiaryBene : bene) {
                                                CtrRelation ctrRelation = new CtrRelation();
                                                //中信登受益人ID
                                                long ctrRelationId = myIdGenerator.nextId();
                                                ctrRelation.setId(ctrRelationId);
                                                ctrRelation.setLogId(ctrLogID);
                                                ctrRelation.setEntityName(benerficiaryBene.getEntityname());
                                                ctrRelation.setEntityType(benerficiaryBene.getEntitytype());
                                                ctrRelation.setRuleId(benerficiaryBene.getRuleid());
                                                ctrRelation.setPartyName(benerficiaryBene.getPartyname());
                                                ctrRelation.setPartyType(benerficiaryBene.getPartytype());
                                                ctrRelation.setCreditCode(benerficiaryBene.getCreditcode());
                                                ctrRelation.setOrganizationCode(benerficiaryBene.getOrganizationcode());
                                                ctrRelation.setRulePathNumber(benerficiaryBene.getRulepathnumber());
                                                ctrRelation.setRulePath(benerficiaryBene.getRulepath());
                                                ctrRelation.setConratePathNumber(benerficiaryBene.getConratepathnumber());
                                                ctrRelation.setConratePath(benerficiaryBene.getConratepath());
                                                ctrRelation.setCirc(benerficiaryBene.getCirc());
                                                ctrRelation.setBjhReason(benerficiaryBene.getBjhreason());
                                                ctrRelation.setSse(benerficiaryBene.getSse());
                                                ctrRelation.setSjsReason(benerficiaryBene.getSjsreason());
                                                ctrRelation.setAccount(benerficiaryBene.getAccount());
                                                ctrRelation.setKjzzReason(benerficiaryBene.getKjzzreason());
                                                ctrRelation.setSehk(benerficiaryBene.getSehk());
                                                ctrRelation.setLjsReason(benerficiaryBene.getLjsreason());
                                                ctrRelation.setStatus(Contant.STATUS);
                                                ctrRelation.setCreateTime(date);
                                                ctrRelation.setUpdateTime(date);
                                                ctrRelation.setCreateUserId(loginUser.getId());
                                                ctrRelation.setUpdateUserId(loginUser.getId());
                                                ctrCtrRelations.add(ctrRelation);
                                            }
                                            //批量新增受益人数据
                                            ctrRelationService.addList(ctrCtrRelations);
                                        }
                                    } else {
                                        //修改中信登接口日志表接口状态等
                                        ctrLog = new CtrLog();
                                        ctrLog.setId(ctrLogID);
                                        if (bene == null) {
                                            ctrLog.setDataCount(0);
                                        } else {
                                            ctrLog.setDataCount(bene.size());
                                        }
                                        ctrLog.setRetContent(relatedParties);
                                        ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                                        ctrLog.setFailReason(relatedPartiesResponseVO.getBody().getResultDetailMsg());
                                        ctrLogService.modifyById(ctrLog);
                                        return new ResponseInfo(Contant.SUCCESS,
                                                relatedPartiesResponseVO.getBody().getResultDetailMsg());
                                    }
                                } else {
                                    //修改中信登接口日志表接口状态为失败，及失败原因
                                    ctrLog = new CtrLog();
                                    ctrLog.setId(ctrLogID);
                                    ctrLog.setRetContent(relatedParties);
                                    ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                                    ctrLog.setFailReason(relatedPartiesResponseVO.getHead().getRetMsg());
                                    ctrLogService.modifyById(ctrLog);
                                    return new ResponseInfo(retCd, relatedPartiesResponseVO.getHead().getRetMsg());
                                }
                            }else {
                                return new ResponseInfo(relatedPartiesResponseVO.getHead().getRetCd(),
                                        relatedPartiesResponseVO.getHead().getRetMsg());
                            }
                        } catch (Exception e) {
                            ctrLog = new CtrLog();
                            ctrLog.setId(ctrLogID);
                            ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                            ctrLog.setFailReason("调用中信登第三方接口(关联方) 调用接口异常");
                            //修改中信登接口日志表 接口状态 为返回失败
                            ctrLogService.modifyById(ctrLog);
                            e.printStackTrace();
                            log.error("调用中信登第三方接口(受益所有人) 调用接口异常{}");
                            return new ResponseInfo("000", "访问中信登第三方接口异常!");
                        }
                    }
                    //修改中信登接口日志表接口状态等
                    ctrLog = new CtrLog();
                    ctrLog.setId(ctrLogID);
                    ctrLog.setDataCount(beneSize);
                    ctrLog.setRetContent(relatedPartiesContent);
                    ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                    if (beneSize == null || beneSize == 0) {
                        ctrLog.setFailReason("查询成功无数据");
                    }
                    ctrLogService.modifyById(ctrLog);
                    if (beneSize == null || beneSize == 0) {
                        return new ResponseInfo(Contant.SUCCESS, ctrLog.getFailReason());
                    } else {
                        // 返回给前端数据
                        CtrRelation ctrRelation = new CtrRelation();
                        ctrRelation.setLogId(ctrLogID);
                        PageResult<CtrRelation> page = pageService.page(relatedPartiesVO.getPageParam(), () -> ctrRelationService.queryList(ctrRelation,
                                relatedPartiesVO.getContent().getRegulatoryRequirementsSelectStatus()));
                        //返回给前端数据
                        PageResult<CtrRelationDTO> relationDTOPageResult = backToFrontEnd(page, ctrLogID);
                        return new ResponseInfo(relationDTOPageResult);
                    }
                }else {
                    RelatedPartiesResponseVO relatedPartiesResponseVO = JSON.parseObject(relatedParties, RelatedPartiesResponseVO.class);
                    RelatedPartiesResponseVO.RelatedPartiesBody body1 = relatedPartiesResponseVO.getBody();
                    if (body1 != null) {
                        String data2 = relatedPartiesResponseVO.getBody().getData();
                        RelatedPartiesResponseVO.BenerficiaryData benerficiaryData1 = null;
                        if (StringUtils.isNotBlank(data2)) {
                            benerficiaryData1 = JSON.parseObject(data2, RelatedPartiesResponseVO.BenerficiaryData.class);
                        }
                        //获取中信登（受益人）结果
                        List<RelatedPartiesResponseVO.RelatedParties> bene = null;
                        if (StringUtils.isNotBlank(data2)) {
                            bene = benerficiaryData1.getRelatedParties();
                        }
                        //获取返回状态
                        String retCd = relatedPartiesResponseVO.getHead().getRetCd();
                        if (retCd.equals(Contant.RET_CD)) {
                            String resultDetailCode = relatedPartiesResponseVO.getBody().getResultDetailCode();
                            if ("00".equals(resultDetailCode)) {
                                List<CtrRelation> ctrCtrRelations = new ArrayList<>();
                                if (bene != null && bene.size() > 0) {
                                    for (RelatedPartiesResponseVO.RelatedParties benerficiaryBene : bene) {
                                        CtrRelation ctrRelation = new CtrRelation();
                                        //中信登受益人ID
                                        long ctrRelationId = myIdGenerator.nextId();
                                        ctrRelation.setId(ctrRelationId);
                                        ctrRelation.setLogId(ctrLogID);
                                        ctrRelation.setEntityName(benerficiaryBene.getEntityname());
                                        ctrRelation.setEntityType(benerficiaryBene.getEntitytype());
                                        ctrRelation.setRuleId(benerficiaryBene.getRuleid());
                                        ctrRelation.setPartyName(benerficiaryBene.getPartyname());
                                        ctrRelation.setPartyType(benerficiaryBene.getPartytype());
                                        ctrRelation.setCreditCode(benerficiaryBene.getCreditcode());
                                        ctrRelation.setOrganizationCode(benerficiaryBene.getOrganizationcode());
                                        ctrRelation.setRulePathNumber(benerficiaryBene.getRulepathnumber());
                                        ctrRelation.setRulePath(benerficiaryBene.getRulepath());
                                        ctrRelation.setConratePathNumber(benerficiaryBene.getConratepathnumber());
                                        ctrRelation.setConratePath(benerficiaryBene.getConratepath());
                                        ctrRelation.setCirc(benerficiaryBene.getCirc());
                                        ctrRelation.setBjhReason(benerficiaryBene.getBjhreason());
                                        ctrRelation.setSse(benerficiaryBene.getSse());
                                        ctrRelation.setSjsReason(benerficiaryBene.getSjsreason());
                                        ctrRelation.setAccount(benerficiaryBene.getAccount());
                                        ctrRelation.setKjzzReason(benerficiaryBene.getKjzzreason());
                                        ctrRelation.setSehk(benerficiaryBene.getSehk());
                                        ctrRelation.setLjsReason(benerficiaryBene.getLjsreason());
                                        ctrRelation.setStatus(Contant.STATUS);
                                        ctrRelation.setCreateTime(date);
                                        ctrRelation.setUpdateTime(date);
                                        ctrRelation.setCreateUserId(loginUser.getId());
                                        ctrRelation.setUpdateUserId(loginUser.getId());
                                        ctrCtrRelations.add(ctrRelation);
                                    }
                                    //批量新增受益人数据
                                    ctrRelationService.addList(ctrCtrRelations);
                                }
                                //修改中信登接口日志表接口状态等
                                ctrLog = new CtrLog();
                                ctrLog.setId(ctrLogID);
                                ctrLog.setDataCount(bene.size());
                                ctrLog.setRetContent(relatedParties);
                                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                                if (bene == null || bene.size() == 0) {
                                    ctrLog.setFailReason("查询成功无数据");
                                }
                                ctrLogService.modifyById(ctrLog);
                                if (bene == null || bene.size() == 0) {
                                    return new ResponseInfo(Contant.SUCCESS, ctrLog.getFailReason());
                                } else {
                                    // 返回给前端数据
                                    CtrRelation ctrRelation = new CtrRelation();
                                    ctrRelation.setLogId(ctrLogID);
                                    PageResult<CtrRelation> page = pageService.page(relatedPartiesVO.getPageParam(), () -> ctrRelationService.queryList(ctrRelation,
                                            relatedPartiesVO.getContent().getRegulatoryRequirementsSelectStatus()));
                                    //返回给前端数据
                                    PageResult<CtrRelationDTO> relationDTOPageResult = backToFrontEnd(page, ctrLogID);
                                    return new ResponseInfo(relationDTOPageResult);
                                }
                            } else {
                                //修改中信登接口日志表接口状态等
                                ctrLog = new CtrLog();
                                ctrLog.setId(ctrLogID);
                                if (bene == null) {
                                    ctrLog.setDataCount(0);
                                } else {
                                    ctrLog.setDataCount(bene.size());
                                }
                                ctrLog.setRetContent(relatedParties);
                                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                                ctrLog.setFailReason(relatedPartiesResponseVO.getBody().getResultDetailMsg());
                                ctrLogService.modifyById(ctrLog);
                                return new ResponseInfo(Contant.SUCCESS,
                                        relatedPartiesResponseVO.getBody().getResultDetailMsg());
                            }
                        } else {
                            //修改中信登接口日志表接口状态为失败，及失败原因
                            ctrLog = new CtrLog();
                            ctrLog.setId(ctrLogID);
                            ctrLog.setRetContent(relatedParties);
                            ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                            ctrLog.setFailReason(relatedPartiesResponseVO.getHead().getRetMsg());
                            ctrLogService.modifyById(ctrLog);
                            return new ResponseInfo(retCd, relatedPartiesResponseVO.getHead().getRetMsg());
                        }
                    } else {
                        return new ResponseInfo(relatedPartiesResponseVO.getHead().getRetCd(),
                                relatedPartiesResponseVO.getHead().getRetMsg());
                    }
                }
            } else {
                ctrLog = new CtrLog();
                ctrLog.setId(ctrLogID);
                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                ctrLog.setFailReason(relatedPartiesResponseVO1.getBody().getResultDetailMsg());
                ctrLog.setDataCount(0);
                ctrLog.setRetContent(relatedParties);
                //修改中信登接口日志表 接口状态 为返回失败
                ctrLogService.modifyById(ctrLog);
                return new ResponseInfo(relatedPartiesResponseVO1.getBody().getResultDetailCode(),
                        relatedPartiesResponseVO1.getBody().getResultDetailMsg());
            }
        } else {
            ctrLog = new CtrLog();
            ctrLog.setId(ctrLogID);
            ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
            ctrLog.setFailReason(relatedPartiesResponseVO1.getHead().getRetMsg());
            ctrLog.setDataCount(0);
            ctrLog.setRetContent(relatedParties);
            //修改中信登接口日志表 接口状态 为返回失败
            ctrLogService.modifyById(ctrLog);
            return new ResponseInfo(relatedPartiesResponseVO1.getHead().getRetCd(),
                    relatedPartiesResponseVO1.getHead().getRetMsg());
        }
    }
    
    
    /**
     * 更新中信登受益人数据
     * @param relatedPartiesVO
     * @return
     */
    @Override
    public ResponseInfo<PageResult<CtrRelationDTO>> updateRelatedParties(ReqDTO<RelatedPartiesVO> relatedPartiesVO) {
        //签名
        String dgtSgnDscMd5 = null;
        //根据公司id或者key到中信登接口日志表查询数据，如果有则返回对应的受益人，如果没有则执行下方法
        String param;
        if (relatedPartiesVO.getContent().getCompId() != null) {
            param = String.valueOf(relatedPartiesVO.getContent().getCompId());
        } else if (StringUtils.isNotBlank(relatedPartiesVO.getContent().getKey())) {
            param = relatedPartiesVO.getContent().getKey();
        } else {
            return new ResponseInfo();
        }
        ResponseInfo<PageResult<CtrRelationDTO>> pageResultResponseInfo = thirdData(param, relatedPartiesVO);
        return pageResultResponseInfo;
    }
    
    /**
     * 关联方数据导出
     * @param relatedPartiesExportVO
     * @param response
     */
    @Override
    public void dataExport(RelatedPartiesExportVO relatedPartiesExportVO, HttpServletResponse response)
            throws IOException {
        //查询日志表中最大的id
        Long id = ctrLogService.queryByMaxId(relatedPartiesExportVO.getCompId(),relatedPartiesExportVO.getKey());
        if(id != null){
            List<CtrRelation> list = ctrRelationService.queryByLogId(id);
            List<RelationExportDTO> relationExportDTOS = new ArrayList<>();
            //序号
            int i = 1;
            if (list != null && list.size() >0){
                for (CtrRelation ctrRelation : list) {
                    RelationExportDTO relationExportDTO = new RelationExportDTO();
                    relationExportDTO.setSerialNumber(i++);
                    relationExportDTO.setPartyName(ctrRelation.getPartyName());
                    relationExportDTO.setPartyType(ctrRelation.getPartyType());
                    relationExportDTO.setCreditCode(ctrRelation.getCreditCode());
                    relationExportDTO.setOrganizationCode(ctrRelation.getOrganizationCode());
                    //符合的监管要求
                    String compWithRegulatoryRequire = compWithRegulatoryRequireData(ctrRelation);
                    relationExportDTO.setCompWithRegulatoryRequire(compWithRegulatoryRequire);
                    //规则路径链中的编码拼接起来
                    String judgmentRule = "";
                    String rulePath = ctrRelation.getRulePath();
                    if(rulePath != null) {
                        String[] split = rulePath.split("-");
                        if (split != null && split.length > 0) {
                            for (String s : split) {
                                String regex = "^[A-Z]{3}[_]([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])$";
                                if (s.matches(regex)) {
                                    judgmentRule += s + "、";
                                }
                            }
                        }
                    }
                    if (StringUtils.isNotBlank(judgmentRule)) {
                        judgmentRule = judgmentRule.substring(0, judgmentRule.length() - 1);
                    }
                    relationExportDTO.setJudgmentRule(judgmentRule);
                    relationExportDTO.setUpdateTime(ctrRelation.getCreateTime());
                    relationExportDTOS.add(relationExportDTO);
                }
            }
            String directory = System.getProperty("java.io.tmpdir");
            File file = new File(directory,"relatedParties.xls");
            //导出数据到本机默认路径
            ExcelUtils.export2Excel(relationExportDTOS,file);
            //下载文件，下载成功后删除文件
            localFileService.download(file.getAbsolutePath(), response);
            try {
                if(!file.delete()){
                    log.error("删除本地临时文件错误：{}" , directory+"/"+file.getName());
                }
            }
            catch (Exception e) {
                log.error("删除本地临时文件错误：{}" , directory+"/"+file.getName());
            }
        }
    }
    
}